#pragma once
#include <iostream>
#include <cstdlib>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "InetAddr.hpp"
#include "Comm.hpp"
#include "Socket.hpp"
#include "Logger.hpp"


class TcpClient
{
    public:
    TcpClient(const std::string& ip,uint16_t port):_tcp(std::make_unique<TcpSocket>()),_addr(port,ip)
    {
        // std::cout << "TcpClient" << std::endl;
        _tcp->BuildClientSocketMethod();
    }

    void Start()
    {
        //不考虑断线重连的情况,连接建立一次后，即可稳定通信
        //while

        // std::cout << "Tcp Start" << std::endl;
        if(!_tcp->Connect(_addr))
        {
            LOG(LogLevel::FATAL) << "client connect error";
            exit(CONNECT_ERR);
        }

        LOG(LogLevel::INFO) << "client connect success";

        //长连接
        while(true)
        {
            std::string inbuffer;
            std::getline(std::cin,inbuffer);
            int n = send(_tcp->SockFd(),inbuffer.c_str(),inbuffer.size(),0);//阻塞式
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "send error";
                exit(1);
            }
            
            char buffer[1024] = {0};
            int sz = read(_tcp->SockFd(),buffer,sizeof(buffer) - 1);
            if(sz > 0)
            {
                buffer[sz] = 0;
                std::cout << "server echo#" << " " << buffer << std::endl;
            }
            else if(sz == 0)
            {
                std::cout << "server quit,me too!" << std::endl;
                exit(0);
            }
            else 
            {
                LOG(LogLevel::ERROR) << "read error";
                exit(1);
            }
        }
    }
    

    
    private:
    std::unique_ptr<Socket> _tcp;//多态机制
    InetAddr _addr;
};